<template>
  <div class="shop-fee-management">

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-card shadow="never">
        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-form-item label="店铺">
            <el-select 
              v-model="searchForm.shopId" 
              placeholder="请选择店铺" 
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="shop in shopList"
                :key="shop.id"
                :label="shop.shopName"
                :value="shop.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="费用类型">
            <el-select 
              v-model="searchForm.feeType" 
              placeholder="请选择费用类型" 
              clearable
              style="width: 150px"
            >
              <el-option label="物业费" value="PROPERTY" />
              <el-option label="水费" value="WATER" />
              <el-option label="电费" value="ELECTRIC" />
              <el-option label="燃气费" value="GAS" />
              <el-option label="卫生费" value="SANITATION" />
            </el-select>
          </el-form-item>
          <el-form-item label="支付状态">
            <el-select 
              v-model="searchForm.paymentStatus" 
              placeholder="请选择支付状态" 
              clearable
              style="width: 120px"
            >
              <el-option label="未支付" :value="0" />
              <el-option label="已支付" :value="1" />
              <el-option label="逾期" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="费用日期">
            <el-date-picker
              v-model="searchForm.feeDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="到期日期">
            <el-date-picker
              v-model="searchForm.dueDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 操作区域 -->
    <div class="operation-area">
      <el-card shadow="never">
        <div class="operation-buttons">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增费用记录
          </el-button>
          <el-button type="success" @click="handleBatchPayment" :disabled="selectedRows.length === 0">
            <el-icon><Money /></el-icon>
            批量支付
          </el-button>
          <el-button type="warning" @click="handleBatchRemind" :disabled="selectedRows.length === 0">
            <el-icon><Bell /></el-icon>
            批量催缴
          </el-button>
          <el-button type="info" @click="handleExport" :disabled="feeList.length === 0">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
          <el-button type="info" @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-area">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-value">{{ formatMoney(stats.totalAmount) }}</div>
              <div class="stats-label">总费用金额(元)</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-value paid">{{ formatMoney(stats.paidAmount) }}</div>
              <div class="stats-label">已支付金额(元)</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-value unpaid">{{ formatMoney(stats.unpaidAmount) }}</div>
              <div class="stats-label">未支付金额(元)</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-value overdue">{{ formatMoney(stats.overdueAmount) }}</div>
              <div class="stats-label">逾期金额(元)</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-card shadow="never">
        <el-table 
          :data="feeList" 
          v-loading="loading"
          stripe
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="shopName" label="店铺名称" min-width="120" />
          <el-table-column prop="feeTypeName" label="费用类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getFeeTypeTagType(row.feeType)">
                {{ row.feeTypeName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="feeAmount" label="费用金额" width="120">
            <template #default="{ row }">
              <span class="money-text">¥{{ formatMoney(row.feeAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="feeDate" label="费用日期" width="120" />
          <el-table-column prop="dueDate" label="到期日期" width="120" />
          <el-table-column prop="paymentDate" label="支付日期" width="120">
            <template #default="{ row }">
              {{ row.paymentDate || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="paymentStatusName" label="支付状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getPaymentStatusTagType(row.paymentStatus)">
                {{ row.paymentStatusName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="paymentMethod" label="支付方式" width="120">
            <template #default="{ row }">
              {{ row.paymentMethod || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="receiptNumber" label="收据号" min-width="120">
            <template #default="{ row }">
              {{ row.receiptNumber || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleView(row)">
                <el-icon><View /></el-icon>
                查看
              </el-button>
              <el-button 
                v-if="row.paymentStatus === 0" 
                type="success" 
                size="small" 
                @click="handlePayment(row)"
              >
                <el-icon><Money /></el-icon>
                支付
              </el-button>
              <el-button 
                v-if="row.paymentStatus === 0" 
                type="warning" 
                size="small" 
                @click="handleRemind(row)"
              >
                <el-icon><Bell /></el-icon>
                催缴
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-card shadow="never">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </div>

    <!-- 费用详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="费用详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <ShopFeeDetail v-if="detailDialogVisible" :fee-id="selectedFeeId" />
    </el-dialog>

    <!-- 费用表单对话框 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="formTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <ShopFeeForm 
        v-if="formDialogVisible" 
        :fee-id="selectedFeeId"
        :mode="formMode"
        @success="handleFormSuccess"
        @cancel="handleFormCancel"
      />
    </el-dialog>

    <!-- 支付对话框 -->
    <el-dialog
      v-model="paymentDialogVisible"
      title="费用支付"
      width="500px"
      :close-on-click-modal="false"
    >
      <ShopFeePayment 
        v-if="paymentDialogVisible" 
        :fee-id="selectedFeeId"
        @success="handlePaymentSuccess"
        @cancel="handlePaymentCancel"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Download, 
  View, 
  Edit, 
  Delete,
  Money,
  Bell
} from '@element-plus/icons-vue'
import ShopFeeDetail from './components/ShopFeeDetail.vue'
import ShopFeeForm from './components/ShopFeeForm.vue'
import ShopFeePayment from './components/ShopFeePayment.vue'
import { shopFeeRecordApi } from '@/api/region/shop-fee-record'
import type { ShopFeeRecordVO, ShopVO, FeeStatistics, PaymentInfo } from './types'
import { formatMoney } from '@/utils'

// 响应式数据
const loading = ref(false)
const feeList = ref<ShopFeeRecordVO[]>([])
const shopList = ref<ShopVO[]>([])
const selectedRows = ref<ShopFeeRecordVO[]>([])

// 搜索表单
const searchForm = reactive({
  shopId: null as number | null,
  feeType: null as string | null,
  paymentStatus: null as number | null,
  feeDateRange: null as [string, string] | null,
  dueDateRange: null as [string, string] | null
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框状态
const detailDialogVisible = ref(false)
const formDialogVisible = ref(false)
const paymentDialogVisible = ref(false)
const selectedFeeId = ref<number | null>(null)
const formMode = ref<'add' | 'edit'>('add')

// 统计数据 - 确保初始值为有效数字
const stats = reactive({
  totalAmount: 0,
  paidAmount: 0,
  unpaidAmount: 0,
  overdueAmount: 0
})

// 计算属性
const formTitle = computed(() => {
  return formMode.value === 'add' ? '新增费用记录' : '编辑费用记录'
})

// 生命周期
onMounted(() => {
  loadFeeList()
  loadShopList()
  loadStatistics()
})

// 方法
const loadFeeList = async () => {
  loading.value = true
  try {
    // 调用真实API
    const response = await shopFeeRecordApi.getPage({
      current: pagination.current,
      size: pagination.size,
      shopId: searchForm.shopId || undefined,
      feeType: searchForm.feeType || undefined,
      paymentStatus: searchForm.paymentStatus || undefined,
      feeDateStart: searchForm.feeDateRange?.[0] || undefined,
      feeDateEnd: searchForm.feeDateRange?.[1] || undefined,
      dueDateStart: searchForm.dueDateRange?.[0] || undefined,
      dueDateEnd: searchForm.dueDateRange?.[1] || undefined
    })
    
    // 检查响应状态，遵循《Element Plus组件编码规范权威标准声明.md》规范
    // 注意：request拦截器已经处理了响应，response直接是data对象
    if (response && response.code === 200) {
      const data = response.data
      console.log('API返回的费用列表数据:', data)
      
      // 数据字段映射和格式化
      feeList.value = data.records || []
      pagination.total = data.total || 0
      pagination.current = data.current || 1
      pagination.size = data.size || 10
      
      console.log('处理后的费用列表:', feeList.value)
      console.log('分页信息:', pagination)
      
      // 如果没有数据，显示提示信息而不是错误
      if (feeList.value.length === 0) {
        console.log('费用列表为空，这是正常情况')
      }
    } else {
      const errorMsg = response?.message || '加载费用列表失败'
      ElMessage.error(errorMsg)
      console.error('API返回错误:', response)
    }
  } catch (error) {
    ElMessage.error('加载费用列表失败')
    console.error('加载费用列表失败:', error)
  } finally {
    loading.value = false
  }
}

const loadShopList = async () => {
  try {
    // 这里需要调用店铺列表API，暂时使用空数组
    // 实际项目中应该有店铺列表API
    shopList.value = []
  } catch (error) {
    ElMessage.error('加载店铺列表失败')
    console.error('加载店铺列表失败:', error)
  }
}

const loadStatistics = async () => {
  try {
    const response = await shopFeeRecordApi.getStatistics({
      shopId: searchForm.shopId || undefined,
      feeType: searchForm.feeType || undefined,
      paymentStatus: searchForm.paymentStatus || undefined
    })
    
    // 检查响应状态，遵循《Element Plus组件编码规范权威标准声明.md》规范
    // 注意：request拦截器已经处理了响应，response直接是data对象
    if (response && response.code === 200) {
      const data = response.data as FeeStatistics
      console.log('API返回的统计数据:', data)
      
      // 数据字段映射和格式化 - 确保数值安全
      stats.totalAmount = Number(data.totalAmount) || 0
      stats.paidAmount = Number(data.paidAmount) || 0
      stats.unpaidAmount = Number(data.unpaidAmount) || 0
      stats.overdueAmount = Number(data.overdueAmount) || 0
      
      console.log('处理后的统计数据:', stats)
    } else {
      console.warn('获取统计数据失败:', response?.message)
      // 统计数据失败时重置为0，不显示错误信息
      stats.totalAmount = 0
      stats.paidAmount = 0
      stats.unpaidAmount = 0
      stats.overdueAmount = 0
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    // 统计数据失败时重置为0，不显示错误信息
    stats.totalAmount = 0
    stats.paidAmount = 0
    stats.unpaidAmount = 0
    stats.overdueAmount = 0
  }
}

const filterFeeList = (data: ShopFeeRecordVO[]) => {
  return data.filter(fee => {
    if (searchForm.shopId && fee.shopId !== searchForm.shopId) return false
    if (searchForm.feeType && fee.feeType !== searchForm.feeType) return false
    if (searchForm.paymentStatus !== null && fee.paymentStatus !== searchForm.paymentStatus) return false
    if (searchForm.feeDateRange && searchForm.feeDateRange.length === 2) {
      const [startDate, endDate] = searchForm.feeDateRange
      if (fee.feeDate < startDate || fee.feeDate > endDate) return false
    }
    return true
  })
}

const calculateStats = (data: ShopFeeRecordVO[]) => {
  stats.totalAmount = data.reduce((sum, fee) => sum + fee.feeAmount, 0)
  stats.paidAmount = data.filter(fee => fee.paymentStatus === 1).reduce((sum, fee) => sum + fee.feeAmount, 0)
  stats.unpaidAmount = data.filter(fee => fee.paymentStatus === 0).reduce((sum, fee) => sum + fee.feeAmount, 0)
  stats.overdueAmount = data.filter(fee => fee.paymentStatus === 2).reduce((sum, fee) => sum + fee.feeAmount, 0)
}

const handleSearch = () => {
  pagination.current = 1
  loadFeeList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    shopId: null,
    feeType: null,
    paymentStatus: null,
    feeDateRange: null,
    dueDateRange: null
  })
  handleSearch()
}

const handleAdd = () => {
  selectedFeeId.value = null
  formMode.value = 'add'
  formDialogVisible.value = true
}

const handleEdit = (row: ShopFeeRecordVO) => {
  selectedFeeId.value = row.id
  formMode.value = 'edit'
  formDialogVisible.value = true
}

const handleView = (row: ShopFeeRecordVO) => {
  selectedFeeId.value = row.id
  detailDialogVisible.value = true
}

const handlePayment = (row: ShopFeeRecordVO) => {
  selectedFeeId.value = row.id
  paymentDialogVisible.value = true
}

const handleRemind = async (row: ShopFeeRecordVO) => {
  try {
    await ElMessageBox.confirm(
      `确定要催缴店铺"${row.shopName}"的${row.feeTypeName}吗？`, 
      '催缴确认', 
      {
        type: 'warning',
        confirmButtonText: '确定催缴',
        cancelButtonText: '取消'
      }
    )
    
    // 调用真实API
    const response = await shopFeeRecordApi.remind(row.id)
    if (response.code === 200) {
      ElMessage.success('催缴通知已发送')
      loadFeeList()
    } else {
      ElMessage.error(response.message || '催缴失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('催缴失败')
      console.error('催缴失败:', error)
    }
  }
}

const handleDelete = async (row: ShopFeeRecordVO) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除店铺"${row.shopName}"的费用记录吗？删除后不可恢复！`, 
      '删除确认', 
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )
    
    // 调用真实API
    loading.value = true
    const response = await shopFeeRecordApi.delete(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadFeeList()
      loadStatistics()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除失败:', error)
    }
  } finally {
    loading.value = false
  }
}

const handleBatchPayment = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要支付的费用记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要批量支付${selectedRows.value.length}条费用记录吗？`, 
      '批量支付确认', 
      {
        type: 'warning',
        confirmButtonText: '确定支付',
        cancelButtonText: '取消'
      }
    )
    
    // 调用真实API
    const response = await shopFeeRecordApi.batchPay({
      ids: selectedRows.value.map(row => row.id),
      paymentInfo: {
        paymentMethod: '批量支付',
        paymentDate: new Date().toISOString().split('T')[0],
        remark: '批量支付操作'
      }
    })
    
    if (response.code === 200) {
      ElMessage.success('批量支付成功')
      loadFeeList()
      loadStatistics()
    } else {
      ElMessage.error(response.message || '批量支付失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量支付失败')
      console.error('批量支付失败:', error)
    }
  }
}

const handleBatchRemind = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要催缴的费用记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要批量催缴${selectedRows.value.length}条费用记录吗？`, 
      '批量催缴确认', 
      {
        type: 'warning',
        confirmButtonText: '确定催缴',
        cancelButtonText: '取消'
      }
    )
    
    // 调用真实API
    const response = await shopFeeRecordApi.batchRemind(selectedRows.value.map(row => row.id))
    
    if (response.code === 200) {
      ElMessage.success('批量催缴成功')
      loadFeeList()
    } else {
      ElMessage.error(response.message || '批量催缴失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量催缴失败')
      console.error('批量催缴失败:', error)
    }
  }
}

const handleExport = async () => {
  try {
    const response = await shopFeeRecordApi.export({
      shopId: searchForm.shopId || undefined,
      feeType: searchForm.feeType || undefined,
      paymentStatus: searchForm.paymentStatus || undefined
    })
    
    if (response.code === 200) {
      ElMessage.success('导出成功')
      // 这里可以处理文件下载
    } else {
      ElMessage.error(response.message || '导出失败')
    }
  } catch (error) {
    ElMessage.error('导出失败')
    console.error('导出失败:', error)
  }
}

const handleRefresh = () => {
  loadFeeList()
  loadStatistics()
}

const handleSelectionChange = (selection: ShopFeeRecordVO[]) => {
  selectedRows.value = selection
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadFeeList()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadFeeList()
}

const handleFormSuccess = () => {
  formDialogVisible.value = false
  loadFeeList()
  ElMessage.success(formMode.value === 'add' ? '新增成功' : '编辑成功')
}

const handleFormCancel = () => {
  formDialogVisible.value = false
}

const handlePaymentSuccess = () => {
  paymentDialogVisible.value = false
  loadFeeList()
  ElMessage.success('支付成功')
}

const handlePaymentCancel = () => {
  paymentDialogVisible.value = false
}

// 工具方法
const getFeeTypeTagType = (feeType: string) => {
  const typeMap = {
    'PROPERTY': 'primary',   // 物业费
    'WATER': 'info',         // 水费
    'ELECTRIC': 'warning',   // 电费
    'GAS': 'success',        // 燃气费
    'SANITATION': 'danger'   // 卫生费
  }
  return typeMap[feeType as keyof typeof typeMap] || 'info'
}

const getPaymentStatusTagType = (status: number) => {
  const typeMap = {
    0: 'danger',  // 未支付
    1: 'success', // 已支付
    2: 'warning'  // 逾期
  }
  return typeMap[status as keyof typeof typeMap] || 'info'
}

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.shop-fee-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.operation-area {
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.stats-area {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
}

.stats-content {
  padding: 20px;
}

.stats-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.stats-value.paid {
  color: #67c23a;
}

.stats-value.unpaid {
  color: #f56c6c;
}

.stats-value.overdue {
  color: #e6a23c;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.table-area {
  margin-bottom: 20px;
}

.pagination-area {
  display: flex;
  justify-content: center;
}

.money-text {
  color: #f56c6c;
  font-weight: 600;
}

:deep(.el-card__body) {
  padding: 16px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>
